package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service(version = "1.0.0")
public class UserLikeApiImpl implements UserLikeApi {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;


    public static final String LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    public static final String NOT_LIKE_REDIS_KEY_PREFIX = "USER_NOT_LIKE_";

    @Override
    public Boolean likeUser(Long userId, Long likeUserId) {
        if (isLike(userId, likeUserId)) {
            return false;
        }
        UserLike userLike = new UserLike();
        userLike.setCreated(System.currentTimeMillis());
        userLike.setId(ObjectId.get());
        userLike.setUserId(userId);
        userLike.setLikeUserId(likeUserId);
        mongoTemplate.save(userLike);
        redisTemplate.opsForHash().put(getLikeRedisKey(userId), String.valueOf(likeUserId), "1");
        if (isNotLike(userId, likeUserId)) {
            String notLikeRedisKey = getNotLikeRedisKey(userId);
            redisTemplate.opsForHash().delete(notLikeRedisKey, String.valueOf(likeUserId));
        }
        return true;
    }


    @Override
    public Boolean notLikeUser(Long userId, Long likeUserId) {
        //判断用户是否已经不喜欢，如果已经不喜欢，就返回
        if (this.isNotLike(userId, likeUserId)) {
            return false;
        }

        //将用户保存到不喜欢列表中
        String redisKey = this.getNotLikeRedisKey(userId);
        String hashKey = String.valueOf(likeUserId);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        //判断用户是否在喜欢列表中，如果存在的话，需要删除数据
        if (this.isLike(userId, likeUserId)) {
            //删除MongoDB数据
            Query query = Query.query(Criteria
                    .where("userId").is(userId)
                    .and("likeUserId").is(likeUserId)
            );
            this.mongoTemplate.remove(query, UserLike.class);

            //删除redis中的数据
            redisKey = this.getLikeRedisKey(userId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);
        }

        return true;
    }

    @Override
    public Boolean isMutualLike(Long userId, Long likeUserId) {
        return this.isLike(userId, likeUserId)
                && this.isLike(likeUserId, userId);
    }

    @Override
    public List<Long> queryLikeList(Long userId) {
        String redisKey = this.getLikeRedisKey(userId);
        Set<Object> keys = this.redisTemplate.opsForHash().keys(redisKey);
        if (CollUtil.isEmpty(keys)) {
            return ListUtil.empty();
        }
        List<Long> result = new ArrayList<>(keys.size());
        for (Object key : keys) {
            result.add(Convert.toLong(key));
        }
        return result;
    }

    @Override
    public List<Long> queryNotLikeList(Long userId) {
        String redisKey = this.getNotLikeRedisKey(userId);
        Set<Object> keys = this.redisTemplate.opsForHash().keys(redisKey);
        if (CollUtil.isEmpty(keys)) {
            return ListUtil.empty();
        }

        List<Long> result = new ArrayList<>(keys.size());
        keys.forEach(o -> result.add(Convert.toLong(o)));
        return result;
    }

    @Override
    public Long queryMutualLikeCount(Long userId) {
        List<Long> likeList = queryLikeList(userId);
        Long count = 0L;
        for (Long like : likeList) {
            String likeRedisKey = getLikeRedisKey(like);
            Boolean hasKey = redisTemplate.opsForHash().hasKey(likeRedisKey, String.valueOf(userId));
            if (hasKey) {
                count++;
            }
        }
        return count;
    }

    @Override
    public Long queryLikeCount(Long userId) {
        String likeRedisKey = getLikeRedisKey(userId);
        return redisTemplate.opsForHash().size(likeRedisKey);

    }

    @Override
    public Long queryFanCount(Long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    @Override
    public PageInfo<UserLike> queryMutualLikeList(Long userId, Integer page, Integer pageSize) {
        List<Long> Ids = queryLikeList(userId);
        Query query = Query.query(Criteria.where("userId").in(Ids)
                .and("likeUserId").is(userId)
        );
        return queryList(query, page, pageSize);
    }

    @Override
    public PageInfo<UserLike> queryLikeList(Long userId, Integer page, Integer pageSize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        PageInfo<UserLike> userLikes = queryList(query, page, pageSize);
        return userLikes;
    }

    @Override
    public PageInfo<UserLike> queryFanList(Long userId, Integer page, Integer pageSize) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        return queryList(query, page, pageSize);
    }

    private PageInfo<UserLike> queryList(Query query, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        query.with(pageRequest);
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        PageInfo<UserLike> userLikePageInfo = new PageInfo<>();
        userLikePageInfo.setPageNum(page);
        userLikePageInfo.setPageSize(pageSize);
        userLikePageInfo.setRecords(userLikes);
        return userLikePageInfo;
    }


    @Override
    public Boolean isLike(Long userId, Long likeUserId) {
        String redisKey = getLikeRedisKey(userId);
        String hashKey = String.valueOf(likeUserId);
        return redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    @Override
    public Boolean isNotLike(Long userId, Long likeUserId) {
        String redisKey = getNotLikeRedisKey(userId);
        String hashKey = String.valueOf(likeUserId);
        return redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    private String getLikeRedisKey(Long userId) {
        return LIKE_REDIS_KEY_PREFIX + userId;
    }

    private String getNotLikeRedisKey(Long userId) {
        return NOT_LIKE_REDIS_KEY_PREFIX + userId;
    }
}
